package com.lee.controller;


import com.lee.entity.Employee;
import com.lee.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    //查找所有用户
    @GetMapping("/emps")
    public ModelAndView findAll(Map<String,Object> map){
        ModelAndView modelAndView = new ModelAndView();
//        int i=1/0;
        List<Employee> all = employeeService.findAll();
        modelAndView.setViewName("list");
        modelAndView.addObject("list",all);
        return modelAndView;
    }
    //添加用户
    @PostMapping("/emp")
    public String addEmp(@Valid Employee employee) {

        employeeService.insertEmployee(employee);
        return "redirect:/emps";
    }

    @GetMapping(value="/emp/{id}")
    public String toUpdate(@PathVariable("id")Integer id,Map<String,Object> map) {
        //获取要修改的员工信息（即指定的一条数据）
//        Employee emp = employeeDao.get(id);
        //把数据放到request域中
        Employee byId = employeeService.findById(id);
        map.put("emp", byId);

        return "update";
    }


    //
    @PostMapping("/empupdate")
    public String updateEmp(@Valid Employee employee ,BindingResult result){
        if(result.hasErrors()){
            //校验失败，应该返回失败，在模态框中显示校验失败的错误信息
            Map<String, Object> map = new HashMap<>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                System.out.println("错误的字段名："+fieldError.getField());
                System.out.println("错误信息："+fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("check");
            modelAndView.addObject("check","请正确输入信息");
            return "mycheck";
        }else {
            System.out.println(employee.toString());
            employeeService.updateEmployee(employee);
            return "redirect:/emps";

        }

    }


    @Transactional
    @GetMapping (value="/empdetele/{id}")
    public String deleteEmpl(@PathVariable("id")Integer id) {
        employeeService.deteleById(id);
        int i=1/0;
        return "redirect:/emps";
    }





}
